package com.example.pjy.controller;

import com.example.pjy.pojo.Result;
import com.example.pjy.pojo.Student;
import com.example.pjy.service.StudentService;
import jakarta.annotation.Resource;
import jdk.jfr.Category;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController//告诉spring是一个控制层
@RequestMapping("/student")//URL总路径叫User
public class StudentController {
    @Resource
    private StudentService studentService;//注入UserService接口



    //把接收到的json转为实体类对象 运行时给的是json
    @PostMapping("/add")
    public Result add(@RequestBody Student student){
        if(studentService.isExist(student.getStudentId())){
            return Result.error("该学号已存在");
        }
        studentService.add(student);
        return Result.success();
    }

    //查询 有主体数据给浏览器响应 主题数据是数组 数组里有多个对象
    @GetMapping("/selectlist")
    public Result<List<Student>> list(){
        List<Student> st= studentService.list();
        return Result.success(st);//结果是数组
    }


    //根据id找学生
    @GetMapping("/detail")
    public Result<Student> detail(Integer studentId){//student响应给前端浏览器是json  id接收前端传来的id
        Student st = studentService.findById(studentId);
        return Result.success(st);//结果是对象
    }


    //把json转为对象
    @PutMapping("/updatest")
    public Result updatest(@RequestBody Student student){
        studentService.updatest(student);
        return Result.success();
    }


    @DeleteMapping("/delete/{studentId}")
    public Result delete(@PathVariable("studentId") Integer studentId){
        if(studentService.isTotalScoreExist(studentId)){
            return Result.error("请先删除总成绩管理的对应记录");
        }
        if (studentId == null) {
            return Result.error("学生ID不能为空");
        }
        studentService.delete(studentId);
        return Result.success("删除成功");
    }





    @GetMapping("/selectbyname")
    public Result<List<Student>> selectbyname(@RequestParam("keyword") String keyword){
        List<Student> st = studentService.selectbyname(keyword);
        return Result.success(st);
    }
}
